// pages/list/list.js
// import IMOperator from "./im-operator";
// import UI from "./ui";
// import MsgManager from "./msg-manager";

const util = require('../../utils/util.js')
import { EnumUserType } from '../../utils/constant.js'

/**
 * 聊天页面
 */
const app = getApp(),url = app.globalData.url;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        textMessage: '',
        chatItems: [],
        // latestPlayVoicePath: '',
        chatStatue: 'open',
        // extraArr: [{
        //     picName: 'choose_picture',
        //     description: '照片'
        // }, {
        //     picName: 'take_photos',
        //     description: '拍摄'
        // }, {
        //     picName: 'close_chat',
        //     description: '自定义功能'
        // }],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      this.userInfo = wx.getStorageSync('userInfo')
      this.userType = wx.getStorageSync("userType")
      this.pInfo = JSON.parse(options.position);
      this.setData({
        pageHeight: wx.getSystemInfoSync().windowHeight,
      });
      let titleName = this.userType === EnumUserType.QiYe ? this.pInfo.name : this.pInfo.companyName
      wx.setNavigationBarTitle({
        title: titleName || '留言板'
      });
      this.bindChatHistory()
    },
    onReady() {
      this.chatInput = this.selectComponent('#chatInput');
    },
    bindChatHistory(){
      let params = {
        qzz_id: this.pInfo.userUid,
        zpz_user_id: this.pInfo.enterpriseUid,
        zw_id: this.pInfo.id,
        pageNum: 0,
        pageSize: 100
      }
      wx.request({
        url: url + 'ly_log_ctro/search_ly_by_qzz_id_zpz_user_id_zw_id',
        method: "GET",
        data:params,
        success: res => {
          let resData = res.data
          if(resData.code != 200){
            this.setData({chatItems:[]})
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
          if(!resData || !resData.list || !resData.list.length){
            return
          }
          let chatItems = resData.list.map(item => {
            let isMine = false
            let headUrl = ''
            if(this.userType === EnumUserType.QiYe){
              isMine = item.lyLb === '招聘者'
              headUrl = isMine ? this.userInfo.logo : '../../img/role_gr.png'
            } 
            if(this.userType === EnumUserType.GeRen ){
              isMine = item.lyLb === '求职者'
              headUrl = isMine ? this.userInfo.avatarUrl : '../../img/role_qy.png'
            }
            return {
              type: "text",// voice,text,images,custom
              showTime: true,
              time: item.lyTime,
              headUrl,
              isMy: isMine,
              content: item.lyNr,
              sendStatus: 'success'
            }
          })
          this.setData({ chatItems })
          this.readLY()
        }
      })
    },
    readLY(){
      let params = {
        qzz_id: this.pInfo.userUid,
        zpz_user_id: this.pInfo.enterpriseUid,
        zw_id: this.pInfo.id,
        zpz_or_qzz: this.userType === EnumUserType.QiYe ? 'zpz' : 'qzz'
      }
      wx.request({
        url: url + 'ly_log_ctro/ly_edit_read',
        method: "GET",
        data:params,
        success: res => { }
      })
    },
    addLY(content){
      let params = {
        qzz_id: this.pInfo.userUid,
        zpz_user_id: this.pInfo.enterpriseUid,
        zw_id: this.pInfo.id,
        ly_lb: this.userType === EnumUserType.QiYe ? '招聘者' : '求职者',
        sf_hf: '否',
        hf_id: '',
        ly_nr: content
      }
      wx.request({
        url: url + 'ly_log_ctro/add_ly',
        method: "GET",
        data: params,
        success: res => { 
          this.data.chatItems.push({
            type: "text",// voice,text,images,custom
            showTime: true,
            time: util.formatTime(new Date()),
            headUrl: this.userType === EnumUserType.QiYe ? this.userInfo.logo : this.userInfo.avatarUrl,
            isMy: true,
            content: content,
            sendStatus:'success'
          })
          this.setData({
            chatItems: this.data.chatItems
          })
        }
      })
    },
    onSendMessageEvent(e) {
      let content = e.detail.value;
      app.validSensWords(content, "留言内容").then(() => {
        this.addLY(content)
      }).catch(() => { })

      // this.data.chatItems.push({
      //   type: "text",// voice,text,images,custom
      //   showTime: true,
      //   time: util.formatTime(new Date()),
      //   headUrl: this.userInfo.avatarUrl,
      //   isMy: true,
      //   content: content,
      //   sendStatus:'success'
      // })
      // this.setData({
      //   chatItems: this.data.chatItems
      // })
    },
    resetInputStatus() {
      this.chatInput.closeExtraView();
    },
    // onVoiceRecordEvent(e) {
    //   const {detail: {recordStatus, duration, tempFilePath, fileSize,}} = e;
    //   if (recordStatus === 2) {
    //       this.msgManager.sendMsg({
    //           type: IMOperator.VoiceType,
    //           content: tempFilePath,
    //           duration: Math.floor(duration / 1000)
    //       });
    //   }
    //   this.msgManager.stopAllVoice();
    // },
    /**
     * 点击extra中的item时触发
     * @param e
     */
    // onExtraItemClickEvent(e) {
    //   console.warn(e);
    //   let chooseIndex = parseInt(e.detail.index);
    //   if (chooseIndex === 2) {
    //       this.myFun();
    //       return;
    //   }
    //   wx.chooseImage({
    //       count: 1, // 默认9
    //       sizeType: ['compressed'],
    //       sourceType: chooseIndex === 0 ? ['album'] : ['camera'],
    //       success: (res) => {
    //           this.msgManager.sendMsg({type: IMOperator.ImageType, content: res.tempFilePaths[0]})
    //       }
    //   });
    // },
    /**
     * 点击extra按钮时触发
     * @param e
     */
    // onExtraClickEvent(e) {
    //   console.log(e);
    // },
    //模拟上传文件，注意这里的cbOk回调函数传入的参数应该是上传文件成功时返回的文件url，这里因为模拟，我直接用的savedFilePath
    // simulateUploadFile({savedFilePath, duration, itemIndex}) {
    //   return new Promise((resolve, reject) => {
    //       setTimeout(() => {
    //           let urlFromServerWhenUploadSuccess = savedFilePath;
    //           resolve({url: urlFromServerWhenUploadSuccess});
    //       }, 1000);
    //   });
    // },

    /**
     * 自定义事件
     */
    // myFun() {
    //     wx.showModal({
    //         title: '小贴士',
    //         content: '演示更新会话状态',
    //         confirmText: '确认',
    //         showCancel: true,
    //         success: (res) => {
    //             if (res.confirm) {
    //                 // this.msgManager.sendMsg({type: IMOperator.CustomType})
    //             }
    //         }
    //     })
    // },

   

    // onUnload() {
    //   this.msgManager.stopAllVoice();
    // },

    // async sendMsg({content, itemIndex}) {
    //   try {
    //       const {msg} = await this.imOperator.onSimulateSendMsg({content})
    //       this.UI.updateViewWhenSendSuccess(msg, itemIndex);
    //       return {msg};
    //   } catch (e) {
    //       console.error(e);
    //       this.UI.updateViewWhenSendFailed(itemIndex);
    //   }
    // },
    /**
     * 重发消息
     * @param e
     */
    // resendMsgEvent(e) {
    //   const itemIndex = parseInt(e.currentTarget.dataset.resendIndex);
    //   const item = this.data.chatItems[itemIndex];
    //   this.UI.updateDataWhenStartSending(item, false, false);
    //   this.msgManager.resend({...item, itemIndex});
    // },
});
